import express from 'express';
import cors from 'cors';
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
import { dbRun, dbGet, dbAll } from './database.js';

const app = express();
const PORT = process.env.PORT || 3001;
const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key';

app.use(cors());
app.use(express.json());

// JWT认证中间件
const authenticateToken = (req, res, next) => {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];

  if (!token) {
    return res.status(401).json({ error: 'Access token required' });
  }

  jwt.verify(token, JWT_SECRET, (err, user) => {
    if (err) {
      return res.status(403).json({ error: 'Invalid token' });
    }
    req.user = user;
    next();
  });
};

// 用户注册
app.post('/api/register', async (req, res) => {
  try {
    const { username, email, password, nickname, gender, age, height, weight } = req.body;
    
    // 检查用户是否已存在
    const existingUser = await dbGet('SELECT * FROM users WHERE username = ? OR email = ?', [username, email]);
    if (existingUser) {
      return res.status(400).json({ error: 'Username or email already exists' });
    }

    // 加密密码
    const hashedPassword = await bcrypt.hash(password, 10);
    
    // 创建用户
    const result = await dbRun(
      'INSERT INTO users (username, email, password, nickname, gender, age, height, weight) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
      [username, email, hashedPassword, nickname, gender, age, height, weight]
    );

    res.status(201).json({ message: 'User created successfully', userId: result.id });
  } catch (error) {
    res.status(500).json({ error: 'Internal server error' });
  }
});

// 用户登录
app.post('/api/login', async (req, res) => {
  try {
    const { username, password } = req.body;
    
    // 查找用户
    const user = await dbGet('SELECT * FROM users WHERE username = ? OR email = ?', [username, username]);
    if (!user) {
      return res.status(400).json({ error: 'Invalid credentials' });
    }

    // 验证密码
    const validPassword = await bcrypt.compare(password, user.password);
    if (!validPassword) {
      return res.status(400).json({ error: 'Invalid credentials' });
    }

    // 生成JWT token
    const token = jwt.sign({ userId: user.id, username: user.username }, JWT_SECRET, { expiresIn: '24h' });
    
    res.json({
      token,
      user: {
        id: user.id,
        username: user.username,
        email: user.email,
        nickname: user.nickname,
        gender: user.gender,
        age: user.age,
        height: user.height,
        weight: user.weight,
        dailyCalorieTarget: user.daily_calorie_target
      }
    });
  } catch (error) {
    res.status(500).json({ error: 'Internal server error' });
  }
});

// 获取食物列表
app.get('/api/foods', authenticateToken, async (req, res) => {
  try {
    const { search, category } = req.query;
    let sql = 'SELECT * FROM foods WHERE 1=1';
    const params = [];

    if (search) {
      sql += ' AND name LIKE ?';
      params.push(`%${search}%`);
    }

    if (category) {
      sql += ' AND category = ?';
      params.push(category);
    }

    sql += ' ORDER BY name';
    const foods = await dbAll(sql, params);
    res.json(foods);
  } catch (error) {
    res.status(500).json({ error: 'Internal server error' });
  }
});

// 获取食物详情
app.get('/api/foods/:id', authenticateToken, async (req, res) => {
  try {
    const food = await dbGet('SELECT * FROM foods WHERE id = ?', [req.params.id]);
    if (!food) {
      return res.status(404).json({ error: 'Food not found' });
    }
    res.json(food);
  } catch (error) {
    res.status(500).json({ error: 'Internal server error' });
  }
});

// 添加饮食记录
app.post('/api/records', authenticateToken, async (req, res) => {
  try {
    const { foodId, portionValue, portionUnit, recordDate, mealType } = req.body;
    const userId = req.user.userId;

    const result = await dbRun(
      'INSERT INTO food_records (user_id, food_id, portion_value, portion_unit, record_date, meal_type) VALUES (?, ?, ?, ?, ?, ?)',
      [userId, foodId, portionValue, portionUnit, recordDate, mealType]
    );

    res.status(201).json({ message: 'Record created successfully', recordId: result.id });
  } catch (error) {
    res.status(500).json({ error: 'Internal server error' });
  }
});

// 获取饮食记录
app.get('/api/records', authenticateToken, async (req, res) => {
  try {
    const { date } = req.query;
    const userId = req.user.userId;

    const records = await dbAll(`
      SELECT fr.*, f.name as food_name, f.calories, f.protein, f.carb, f.fat, f.unit as food_unit
      FROM food_records fr
      JOIN foods f ON fr.food_id = f.id
      WHERE fr.user_id = ? AND fr.record_date = ?
      ORDER BY fr.created_at DESC
    `, [userId, date]);

    res.json(records);
  } catch (error) {
    res.status(500).json({ error: 'Internal server error' });
  }
});

// 更新饮食记录
app.put('/api/records/:id', authenticateToken, async (req, res) => {
  try {
    const { portionValue, portionUnit, mealType } = req.body;
    const recordId = req.params.id;
    const userId = req.user.userId;

    // 检查记录是否存在且属于当前用户
    const existingRecord = await dbGet('SELECT * FROM food_records WHERE id = ? AND user_id = ?', [recordId, userId]);
    if (!existingRecord) {
      return res.status(404).json({ error: 'Record not found' });
    }

    await dbRun(
      'UPDATE food_records SET portion_value = ?, portion_unit = ?, meal_type = ? WHERE id = ?',
      [portionValue, portionUnit, mealType, recordId]
    );

    res.json({ message: 'Record updated successfully' });
  } catch (error) {
    res.status(500).json({ error: 'Internal server error' });
  }
});

// 删除饮食记录
app.delete('/api/records/:id', authenticateToken, async (req, res) => {
  try {
    const recordId = req.params.id;
    const userId = req.user.userId;

    // 检查记录是否存在且属于当前用户
    const existingRecord = await dbGet('SELECT * FROM food_records WHERE id = ? AND user_id = ?', [recordId, userId]);
    if (!existingRecord) {
      return res.status(404).json({ error: 'Record not found' });
    }

    await dbRun('DELETE FROM food_records WHERE id = ?', [recordId]);

    res.json({ message: 'Record deleted successfully' });
  } catch (error) {
    res.status(500).json({ error: 'Internal server error' });
  }
});

// 获取历史记录（分页）
app.get('/api/history', authenticateToken, async (req, res) => {
  try {
    const { page = 1, limit = 10 } = req.query;
    const userId = req.user.userId;
    const offset = (page - 1) * limit;

    const records = await dbAll(`
      SELECT fr.*, f.name as food_name, f.calories, f.protein, f.carb, f.fat
      FROM food_records fr
      JOIN foods f ON fr.food_id = f.id
      WHERE fr.user_id = ?
      ORDER BY fr.record_date DESC, fr.created_at DESC
      LIMIT ? OFFSET ?
    `, [userId, limit, offset]);

    const totalCount = await dbGet('SELECT COUNT(*) as count FROM food_records WHERE user_id = ?', [userId]);

    res.json({
      records,
      pagination: {
        currentPage: parseInt(page),
        totalPages: Math.ceil(totalCount.count / limit),
        totalRecords: totalCount.count
      }
    });
  } catch (error) {
    res.status(500).json({ error: 'Internal server error' });
  }
});

// 获取用户信息
app.get('/api/user', authenticateToken, async (req, res) => {
  try {
    const user = await dbGet('SELECT id, username, email, nickname, gender, age, height, weight, daily_calorie_target FROM users WHERE id = ?', [req.user.userId]);
    if (!user) {
      return res.status(404).json({ error: 'User not found' });
    }
    res.json(user);
  } catch (error) {
    res.status(500).json({ error: 'Internal server error' });
  }
});

// 更新用户信息
app.put('/api/user', authenticateToken, async (req, res) => {
  try {
    const { nickname, gender, age, height, weight, dailyCalorieTarget } = req.body;
    const userId = req.user.userId;

    await dbRun(
      'UPDATE users SET nickname = ?, gender = ?, age = ?, height = ?, weight = ?, daily_calorie_target = ? WHERE id = ?',
      [nickname, gender, age, height, weight, dailyCalorieTarget, userId]
    );

    res.json({ message: 'User information updated successfully' });
  } catch (error) {
    res.status(500).json({ error: 'Internal server error' });
  }
});

app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});